package initialize

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"sheep_script/global"
)

func InitDB() {
	// 定义数据库连接信息
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%d)/%v?charset=%v&parseTime=True&loc=Local",
		global.Config.Mysql.Username,
		global.Config.Mysql.Password,
		global.Config.Mysql.Host,
		global.Config.Mysql.Port,
		global.Config.Mysql.Database,
		global.Config.Mysql.Charset)
	fmt.Println("dsn:", dsn)
	// 连接数据库
	var err error
	global.Mysql, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
	}
	// 检查连接是否成功
	sqlDB, err := global.Mysql.DB()
	if err != nil {
		log.Fatalf("failed to get SQL database instance: %v", err)
	}
	// 测试数据库连接
	err = sqlDB.Ping()
	if err != nil {
		log.Fatalf("failed to ping database: %v", err)
	}
	log.Println("Connected to the database!")
}
